<?php namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Cache;
use Exception;
use Log;

/**
 * 系统设置
 * Class Setting
 *
 * @package App\Models
 * @property int $id
 * @property string $name
 * @property string $value
 * @property string $created_at
 * @property string $updated_at
 * @method static \Illuminate\Database\Query\Builder|\App\Models\Setting whereId($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Models\Setting whereName($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Models\Setting whereValue($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Models\Setting whereCreatedAt($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Models\Setting whereUpdatedAt($value)
 * @mixin \Eloquent
 */
class Setting extends Model
{
    protected $fillable = ['name', 'value'];

    /**
     * 更新缓存
     */
    public static function updateCache()
    {
        $settings = self::all()->lists('value', 'name');
        foreach ($settings as $varName => $varValue) {
            Cache::forever('setting.' . $varName, $varValue);
        }
    }

    /**
     * 获取单个配置值
     * @param $name
     * @return mixed
     */
    public static function getOne($name)
    {
        return Cache::rememberForever('setting.' . $name, function () use ($name) {
            $model = self::where('name', $name)->first();
            if ($model) {
                return $model->value;
            } else {
                return null;
            }
        });
    }

    /**
     * 保存单个配置值
     * @param $name
     * @param $value
     * @throws Exception
     */
    public static function saveOne($name, $value)
    {
        $model = self::where('name', $name)->first();
        if (!$model) {
            $model = new Setting();
            $model->name = $name;
        }

        $model->value = $value;
        if (!$model->save()) {
            Log::info($model->getErrors());
            throw new Exception('保存失败。');
        }
    }
}